package com.jt.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.User;
import com.jt.service.DubboUserService;
import com.jt.utils.CookieUtil;
import com.jt.utils.ThreadLocalUtil;
import com.jt.vo.SysResult;
import com.jt.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisCluster;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author dc
 * @Classname UserController
 * @Date 2020/2/24 14:43
 */
@RequestMapping("/user")
@Controller
public class UserController {

    /**不需要先启动生产者*/
    @Reference(check = false)
    private DubboUserService userService;

    @Autowired
    private JedisCluster redis;



    /**
     * 跳转注册,登录页面,修改/忘记密码
     * @param module
     * @return
     */
    @RequestMapping("/{module}")
    public String module(@PathVariable String module){
        return module;
    }

    /**
     * 利用dubbo进行用户注册
     * @return
     */
    @RequestMapping("/doRegister")
    @ResponseBody
    public SysResult doRegister(UserVO userVO){
        userService.saveUser(userVO);
        return SysResult.success();
    }

    /**
     * 利用dubbo实现用户单点登录
     * 1.url:http://www.jt.com/user/doLogin
     * 2.params:username,password
     * 3.返回值SysResult对象
     * 业务:校验ticket
     * @return
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public SysResult doLogin(User user, HttpServletResponse response,HttpSession httpSession,String authcode){
        String codeSession = (String)httpSession.getAttribute("code");
        if (authcode!=null&&authcode.equals(codeSession)){
            String ticket =userService.findUserByUP(user);
            if(StringUtils.isEmpty(ticket)){
                return SysResult.fail("账号或密码不正确");
            }
            //如果ticket有值,则将数据保存到cookie中
            Cookie cookie = new Cookie("JT_TICKET",ticket);
            //设定cookie的共享,在所有jt.com结尾的网站共享
            cookie.setDomain("jt.com");
            //设定cookie权限,所有请求路径都可以访问
            cookie.setPath("/");
            //设定超时时间 一个小时
            cookie.setMaxAge(3600);
            response.addCookie(cookie);
            //登录成功清除验证码
            httpSession.removeAttribute("code");
            return SysResult.success();
        }else {
            return SysResult.fail("验证码错误");
        }
    }

    /**
     * 实现用户的退出操作
     * 需求分析:
     * 1.当用户点击退出按钮时,应该重定向到系统首页
     * 2.根据cookie查询ticket
     * 3.redis缓存 根据ticket
     * 4.删除cookie
     * @return 重定向到系统首页
     */
    @RequestMapping("/logout")
    public String doLogout(HttpServletResponse response, HttpServletRequest request) {
        String ticket = CookieUtil.getCookieValue(request, "JT_TICKET");
        //2.判断是否成功获取ticket信息
        if (!StringUtils.isEmpty(ticket)) {
            //删除redis中的数据.
            redis.del(ticket);
            CookieUtil.deleteCookie(response, "JT_TICKET", "jt.com", "/");
        }
        //跳转系统首页
        return "redirect:/";
    }

    @RequestMapping("/myInfo")
    public String doMyInfo(HttpServletRequest request){

        return "my-info";
    }

    @RequestMapping("/myInfoImg")
    public String doMyInfoImg(HttpServletRequest request){

        return "my-info-img";
    }
    @RequestMapping("/myInfoMore")
    public String doMyInfoMore(HttpServletRequest request){

        return "my-info-more";
    }

    @RequestMapping("/getCode")
    public void getCode(HttpSession session, HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(130, 34, 4, 40);
        //得到验证码存入session
        String code = captcha.getCode();
        session.setAttribute("code", code);
        //获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //写入到输出流
        captcha.write(outputStream);
        outputStream.close();
    }

    /**
     * 修改/忘记密码  opt 1忘记，2修改
     * @param userVO
     * @return
     */
    @RequestMapping("/updatePwd/{opt}")
    @ResponseBody
    public SysResult doUpdatePwd(UserVO userVO){
        if ("2".equals(userVO.getOpt())){
            Long id = ThreadLocalUtil.getUser().getId();
            userVO.setId(id);
        }
        userService.updateByPwd(userVO);
        return SysResult.success();
    }
}
